<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请填写正确的手机号'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '请填写正确的验证码' }
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="加载中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '../../api/login'
import { saveToken } from '../../utils/token'
export default {
  name: 'login',
  data () {
    return {
      isLoading: false,
      mobile: '18888888888',
      code: '246810'
    }
  },
  methods: {
    onSubmit (values) {
      console.log('submit', values)
      this.isLoading = true
      userLogin(values)
        .then(data => {
          console.log(data)
          saveToken(data.data.data)
          // this.$router.push({ path: '/index' })
          if (this.$route.query.back) {
            // 原路返回
            this.$router.push({ path: this.$route.query.back })
          } else {
            // query.back没有值就跳转首页
            this.$router.push({ path: '/index' })
          }
          this.$toast.success('登录成功')
          this.isLoading = false
        })
        .catch(errRes => {
          // console.log('errRes:', errRes)
          this.$toast.fail('验证码有误!')
          // 关闭loading 和 禁用y
          this.isLoading = false
          // this.isDisabled = false
        })
    }
  }
}
</script>

<style lang="less">
.van-nav-bar__content {
  background-color: skyblue;
}
.van-nav-bar__content .van-nav-bar__title {
  color: white;
}
</style>
